package com.hjx.hutool;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.db.Entity;
import cn.hutool.db.SqlRunner;
import cn.hutool.db.handler.RsHandler;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.sql.Blob;
import java.sql.ResultSet;
import java.sql.SQLException;

public class PicTransfer {
    private static SqlRunner runner = SqlRunner.create();
    private static String destDir = "C:/pic";

    public static void main(String[] args) throws SQLException {
        runner.find(
                CollectionUtil.newArrayList("task_key", "status_code", "interactive_code", "interactive_ext_data"),
                Entity.create("t_task_status")
                        .set("task_key", "18080716WECHAT8T6Z9pd9"),
                new RsHandler<String>(){
                    @Override
                    public String handle(ResultSet rs) throws SQLException {
                        int times = 1;
                        while(rs.next()){
                            if(rs.getBlob("interactive_ext_data") != null) {
                                save(rs, times);
                                times++;
                            }
                        }
                        return null;
                    }
                }
        );
    }

    private static void save(ResultSet rs, int times) throws SQLException{


        Blob blob = rs.getBlob("interactive_ext_data");

        String json = new String(blob.getBytes(1, (int) blob.length()));
//        System.out.println(json);
        JSONObject jsonObject = JSON.parseObject(json);
        if(jsonObject.get("list") == null){
            return;
        }
        int i = 1;
        for (Object base64 : (JSONArray)jsonObject.get("list")){

            String path = StrUtil.format("{}/{}-{}-{}.jpg", destDir, rs.getString("task_key"), times, i++);
            FileUtil.writeBytes(Base64.decode(base64.toString()), path);
        }

//        FileUtil.writeFromStream(.getBinaryStream(), path);
    }
}